import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/my/register_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

class MemberManagementPage extends StatefulWidget {
  const MemberManagementPage({super.key});

  @override
  // ignore: library_private_types_in_public_api
  _MemberManagementPageState createState() => _MemberManagementPageState();
}

class _MemberManagementPageState extends State<MemberManagementPage>
    with SingleTickerProviderStateMixin {
  String? memberType;
  String? activeUntil;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _getType();
    });
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('MemberShip Management'.t(context)),
        backgroundColor: themeProvider.mainColor,
      ),
      body: Column(
        children: [
          const SizedBox(height: 20),
          _myContainer('Account Status'.t(context), memberType ?? ''),
          const SizedBox(height: 20),
          _myContainer('Until'.t(context), activeUntil ?? 'NULL'),
          const SizedBox(height: 80),
          _myContainer2('Free Plan'.t(context), 'Downgrade'.t(context), () {
            _editType('normal');
          }),
          const SizedBox(height: 10),
          _myContainer2('Premium'.t(context), 'Selected'.t(context), () {
            _editType('vip');
          }),
        ],
      ),
    );
  }

  Widget _myContainer(String title, String content) {
    return Container(
      margin: const EdgeInsets.only(left: 60, right: 60),
      padding: const EdgeInsets.only(top: 10, bottom: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: Colors.grey,
        ),
        color: Colors.white,
      ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              '$title: $content',
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  Widget _myContainer2(
      String title, String buttonText, VoidCallback onPressed) {
    return Row(
      children: [
        Expanded(
          flex: 6,
          child: Container(
            margin: const EdgeInsets.only(left: 60),
            padding: const EdgeInsets.only(top: 10, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                color: Colors.grey,
              ),
              color: Colors.white,
            ),
            child: Text(
              title,
              textAlign: TextAlign.center,
            ),
          ),
        ),
        Expanded(
            flex: 4,
            child: GestureDetector(
              onTap: () {
                onPressed();
              },
              child: Container(
                margin: const EdgeInsets.only(right: 60),
                padding: const EdgeInsets.only(top: 10, bottom: 10),
                decoration: BoxDecoration(
                  border: Border.all(
                    color: Colors.grey,
                  ),
                  color: Colors.white,
                ),
                child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      onPressed();
                    },
                    child: Text(
                      buttonText,
                      textAlign: TextAlign.center,
                    )),
              ),
            ))
      ],
    );
  }

  Future<void> _getType({bool isNeedShowMsg = true}) async {
    const url = '/get_member_type';
    String token = SpUtil.getString('token') ?? '';
    var response = await DioHttp.of(context).get(url, null, token);
    var resString = json.decode(response.toString());
    if (isNeedShowMsg) {
      Fluttertoast.showToast(msg: resString['msg']);
    }
    if (resString['code'] == 200) {
      setState(() {
        memberType = resString['data']['memberType'];
        activeUntil = resString['data']['activeUntil'];

        /// 把memberType 写进缓存
        UserModel userModel = SpUtil.getObj('userModel', (map) {
          return UserModel.fromJson(map as Map<String, dynamic>);
        })!;
        userModel.memberType = memberType;
        SpUtil.putObject('userModel', userModel);
      });
    }
  }

  Future<void> _editType(String type) async {
    const url = '/update_member_type';
    String token = SpUtil.getString('token') ?? '';

    var params = {
      'memberType': type,
    };
    var response = await DioHttp.of(context).put(url, params, token);
    var resString = json.decode(response.toString());
    Fluttertoast.showToast(msg: resString['msg']);
    if (resString['code'] == 200) {
      _getType(isNeedShowMsg: false);
    }
  }
}
